# app/__init__.py
import os
from datetime import timedelta

import redis
from flask import Flask, request
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from loguru import logger
from config import Config
from app.log_service import LogService

db = SQLAlchemy()
redis_host_url = os.getenv('REDIS_URL', 'localhost')
redis_client = redis.StrictRedis(host=redis_host_url, port=6379, db=0, decode_responses=True)


def create_app():
    app = Flask(__name__, static_folder='mini12306')
    CORS(app)
    app.app_context().push()
    app.config.from_object(Config)
    # 设置jwt token有效时间
    app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=30)
    db.init_app(app)
    Migrate(app, db)
    JWTManager(app)
    LogService.configure_logging()

    # routes
    from app.login_manager import login_bp
    from app.passenger_manager import register_bp
    from app.query_manager import query_bp
    from app.station_manager import station_bp
    from app.mobile_server import mobile_bp
    from app.train_manager import trains_bp
    from app.bank_server import bank_bp
    from app.id_card_server import id_card_bp
    from app.order_manager import order_bp

    app.register_blueprint(login_bp)
    app.register_blueprint(register_bp)
    app.register_blueprint(query_bp)
    app.register_blueprint(station_bp)
    app.register_blueprint(mobile_bp)
    app.register_blueprint(trains_bp)
    app.register_blueprint(bank_bp)
    app.register_blueprint(id_card_bp)
    app.register_blueprint(order_bp)

    return app
